
use anyhow;
use apiexts::CustomResourceDefinition;
use either::Either::{Left, Right};
use futures::{StreamExt, TryStreamExt};
use k8s_openapi::api::apps::v1::{Deployment, DeploymentSpec, DeploymentStatus};
use k8s_openapi::api::core::v1::Pod;
use k8s_openapi::api::core::v1::Service;
use k8s_openapi::apiextensions_apiserver::pkg::apis::apiextensions::v1beta1 as apiexts;
use kube::client::ConfigExt;
use kube::{
    self,
    api::{Api, DeleteParams, ListParams, Patch, PatchParams, PostParams, ResourceExt, WatchEvent},
    core::crd::v1beta1::CustomResourceExt,
    Client, Config, CustomResource,
};
use kube_runtime::{utils::try_flatten_applied, watcher};
use schemars::JsonSchema;
use serde::{Deserialize, Serialize};
use serde_json::json;
use std::time::Duration;
use tokio::time::sleep;
use tracing;
use tracing_subscriber;
use hyper::client::connect::HttpConnector;
use hyper_tls::{native_tls::TlsConnector, HttpsConnector};
use serde_json;
use std::process::Command;
use std::collections::HashMap;
//初始化k8s客户端
pub async fn init_k8s_client() ->Result<Client,anyhow::Error> {
    //获取本地 kubeconfig
    let mut config = Config::infer().await?;

    //不验证tls证书
    config.accept_invalid_certs = true;
    //tracing::info!("config: {:?}", &config);

    let tls = TlsConnector::from(config.native_tls_connector()?);

    let mut http = HttpConnector::new();
    //不限制只用http（可以用 https）
    http.enforce_http(false);
    let https = HttpsConnector::from((http, tls.into()));

    let service = tower::ServiceBuilder::new()
        //kube-api-server地址
        .layer(
            tower::ServiceBuilder::new()
                .layer(config.base_uri_layer())
                .into_inner(),
        )
        //token验证（使用 kubeconfug）
        .option_layer(config.auth_layer()?)
        .service(hyper::Client::builder().build(https));
    //客户端
    let client = Client::new(service, config.default_namespace.clone());

    Ok(client)
}

//获取节点监控指标
pub fn get_nodes_metrics() -> HashMap<String,f64> {
    let output =Command::new("cmd").args(["/C", "kubectl get --raw /apis/metrics.k8s.io/v1beta1/nodes"]).output().expect("cmd exec error!");
    println!("{:?}",&output);
    println!("{:?}",&output.stdout);
    let output_str = String::from_utf8(output.stdout).unwrap();
    println!("{:?}",&output_str);
    let node_metrics_list : serde_json::Value =serde_json::from_str(&output_str).unwrap();
    println!("{:?}",&node_metrics_list);
    println!("{:?}",&node_metrics_list.get("items".to_owned()));
    let items =node_metrics_list.get("items".to_owned()).unwrap().as_array().unwrap();

    let mut map: HashMap<String, f64> = HashMap::new();
    for item in items {
        
        let nodename =item.get("metadata".to_owned()).unwrap().get("name".to_owned()).unwrap().as_str().unwrap();

        let cpu_str = item.get("usage".to_owned()).unwrap().get("cpu".to_owned()).unwrap().as_str().unwrap();
        let memory_str = item.get("usage".to_owned()).unwrap().get("memory".to_owned()).unwrap().as_str().unwrap();

        map.insert(format!("{}_cpu",&nodename),  (cpu_str.replace("n", "").parse::<f64>().unwrap()/ 1000000000.00));
        map.insert(format!("{}_memory",&nodename),  (memory_str.replace("Ki", "").parse::<f64>().unwrap()/ 1000.00));

    }

    map


}